<script setup>
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { getArticleList, createArticle } from '@/api/article';

// 导入组件化的子组件
import {
  ForumHeader,
  ForumActions,
  CategorySidebar,
  PostsList,
  CreatePostModal
} from '@/components/forum';

const { t } = useI18n();
const sectionRef = ref(null);
const isVisible = ref(false);
const activeCategory = ref('all');
const searchQuery = ref('');
const showCreatePost = ref(false);
const isLoading = ref(false);
const loadError = ref(null);

// 引入头像图片
import avatar1 from '@/assets/home/avatar1.jpg';
import avatar2 from '@/assets/home/avatar2.jpg';
import avatar3 from '@/assets/home/avatar3.jpg';
import avatar4 from '@/assets/home/avatar4.jpg';
import avatar5 from '@/assets/home/avatar5.jpg';
import avatar6 from '@/assets/home/avatar6.jpg';

// 模拟用户数据
const users = {
  user1: { name: 'Sarah Johnson', avatar: avatar1, country: 'USA' },
  user2: { name: 'Michael Chen', avatar: avatar2, country: 'Canada' },
  user3: { name: 'Elena Petrova', avatar: avatar3, country: 'Russia' },
  user4: { name: 'Carlos Rodriguez', avatar: avatar4, country: 'Spain' },
  user5: { name: 'Akira Tanaka', avatar: avatar5, country: 'Japan' },
  user6: { name: 'Li Wei', avatar: avatar6, country: 'China' },
};

// 论坛帖子数据
const forumPosts = ref([]);

// 论坛分类
const categories = [
  { id: 'all', name: 'All Topics', icon: '📑' },
  { id: 'travel', name: 'Travel Tips', icon: '🧳' },
  { id: 'food', name: 'Food & Cuisine', icon: '🍜' },
  { id: 'transportation', name: 'Transportation', icon: '🚆' },
  { id: 'practical', name: 'Practical Info', icon: '📱' },
  { id: 'safety', name: 'Safety & Health', icon: '🛡️' },
  { id: 'technology', name: 'Tech & Apps', icon: '📲' },
  { id: 'general', name: 'General Discussion', icon: '💬' },
];

// 获取文章列表
const fetchArticles = async () => {
  isLoading.value = true;
  loadError.value = null;
  
  try {
    // 调用API获取文章数据
    const { data } = await getArticleList();
    
    // 处理获取到的数据
    forumPosts.value = data.map(article => {
      // 保存原始数据
      const originalData = { ...article };
      
      // 处理用户ID，确保格式一致
      let author = article.userId;
      // 如果userId是数字，则格式化为"userX"格式
      if (typeof author === 'number' || !isNaN(Number(author))) {
        author = `user${author}`;
      }
      
      // 转换为前端需要的格式
      return {
        id: article.id,
        author: author,
        title: article.title,
        content: article.richContent,
        likes: article.likeCount || 0,
        date: article.createTime,
        pinned: article.isTop || false,
        category: article.category || 'general', // 默认分类
        views: article.viewCount || 0,
        comments: article.commentCount || 0,
        // 存储原始数据，方便在其他组件中使用
        originalData
      };
    });
    
    // 控制台输出检查数据结构
    console.log('处理后的文章数据:', forumPosts.value);
  } catch (error) {
    console.error('获取文章列表失败:', error);
    forumPosts.value = []; // 确保发生错误时重置为空数组
    loadError.value = '获取论坛数据失败，请稍后再试';
  } finally {
    isLoading.value = false;
  }
};

// 过滤显示的帖子
const filteredPosts = computed(() => {
  // 确保forumPosts.value是数组
  if (!Array.isArray(forumPosts.value)) {
    console.warn('forumPosts.value不是数组，返回空数组');
    return [];
  }
  
  return forumPosts.value.filter(post => {
    if (!post) return false;
    
    const matchesCategory = activeCategory.value === 'all' || 
                          (post.category && post.category === activeCategory.value);
    
    const matchesSearch = (post.title && post.title.toLowerCase().includes(searchQuery.value.toLowerCase())) || 
                         (post.content && post.content.toLowerCase().includes(searchQuery.value.toLowerCase()));
    
    return matchesCategory && matchesSearch;
  });
});

// 创建新帖子
const createPost = async (newPostData) => {
  if (newPostData.title.trim() && newPostData.content.trim()) {
    try {
      // 准备发送到后端的数据
      const postData = {
        title: newPostData.title,
        content: newPostData.content, // 富文本HTML内容，API会转换为richContent
        category: newPostData.category,
        // 假设当前用户ID为1，实际项目中应从用户会话或存储中获取
        userId: 1
      };
      
      const response = await createArticle(postData);
      
      // 如果后端返回了新创建的帖子数据，则直接使用
      if (response.data) {
        // 将后端返回的数据转换为我们组件使用的格式
        const newPost = {
          id: response.data.id || new Date().getTime(),
          title: response.data.title || newPostData.title,
          content: response.data.richContent || newPostData.content,
          author: `user${response.data.userId || 1}`,
          category: response.data.category || newPostData.category,
          likes: response.data.likeCount || 0,
          comments: response.data.commentCount || 0,
          views: response.data.viewCount || 0,
          date: response.data.createTime || new Date().toISOString(),
          pinned: false, // 默认不置顶
          originalData: response.data
        };
        
        forumPosts.value.unshift(newPost);
      } else {
        // 如果后端只返回成功状态但没有返回数据，则使用本地构建的数据对象
        const post = {
          id: new Date().getTime(),
          title: newPostData.title,
          content: newPostData.content,
          author: 'user1',
          category: newPostData.category,
          likes: 0,
          comments: 0,
          views: 0,
          date: new Date().toISOString(),
          pinned: false
        };
        forumPosts.value.unshift(post);
      }
      
      showCreatePost.value = false;
    } catch (error) {
      console.error('创建帖子失败:', error);
      alert('创建帖子失败，请稍后再试');
    }
  }
};

// 打开创建帖子弹窗
const openCreatePostModal = () => {
  showCreatePost.value = true;
};

// 更新搜索内容
const updateSearchQuery = (query) => {
  searchQuery.value = query;
};

onMounted(() => {
  // 监听页面可见性
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        isVisible.value = true;
        observer.disconnect();
      }
    });
  }, { threshold: 0.1 });
  
  if (sectionRef.value) {
    observer.observe(sectionRef.value);
  }
  
  // 获取文章列表
  fetchArticles();
});
</script>

<template>
  <section ref="sectionRef" class="forum-section">
    <div class="forum-container">
      <!-- 使用论坛头部组件 -->
      <ForumHeader :is-visible="isVisible" />
      
      <!-- 使用论坛操作组件 -->
      <ForumActions 
        :is-visible="isVisible"
        @update:search-query="updateSearchQuery"
        @create-post="openCreatePostModal"
      />
      
      <div v-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载论坛数据中...</p>
      </div>
      
      <div v-else-if="loadError" class="error-container">
        <p class="error-message">{{ loadError }}</p>
        <button class="retry-button" @click="fetchArticles">重试</button>
      </div>
      
      <div v-else class="forum-content" :class="{ 'animate': isVisible }">
        <!-- 使用分类侧边栏组件 -->
        <CategorySidebar 
          :categories="categories"
          :active-category="activeCategory"
          :forum-posts="forumPosts"
          @update:active-category="activeCategory = $event"
        />
        
        <!-- 使用帖子列表组件 -->
        <PostsList 
          :posts="filteredPosts"
          :users="users"
          :categories="categories"
          :active-category="activeCategory"
        />
      </div>
    </div>
    
    <!-- 使用创建帖子弹窗组件 -->
    <CreatePostModal
      :show="showCreatePost"
      :categories="categories"
      @close="showCreatePost = false"
      @create-post="createPost"
    />
  </section>
</template>

<style scoped>
/* 论坛部分的基础样式 */
.forum-section {
  width: 100%;
  background-color: #ffffff;
  padding: 80px 0;
  position: relative;
  overflow: hidden;
}

.forum-container {
  max-width: 1600px;
  width: 100%;
  margin: 0 auto;
  padding: 0 20px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #00c389;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态样式 */
.error-container {
  text-align: center;
  padding: 40px 0;
}

.error-message {
  color: #e74c3c;
  font-size: 1.1rem;
  margin-bottom: 20px;
}

.retry-button {
  padding: 10px 25px;
  background-color: #00c389;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.retry-button:hover {
  background-color: #00a873;
}

/* 主要内容区样式 */
.forum-content {
  display: flex;
  gap: 30px;
  opacity: 0;
  transform: translateY(30px);
  transition: all 0.8s ease 0.4s;
}

.forum-content.animate {
  opacity: 1;
  transform: translateY(0);
}

/* 响应式样式 */
@media (max-width: 1200px) {
  .forum-content {
    flex-direction: column;
  }
}
</style> 